package com.briup.service.impl;

import com.alibaba.excel.EasyExcel;
import com.briup.bean.Category;
import com.briup.bean.Ext.CategoryExt;
import com.briup.mapper.CategoryMapper;
import com.briup.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.briup.util.CategoryListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author syh
 * @since 2024-09-10
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {
    @Autowired
    private CategoryMapper mapper;



    @Override
    public List<CategoryExt> data() {
        List<Category> list = mapper.selectList(null);
        List<CategoryExt> resultList = new ArrayList<>();
        for (Category category : list) {
            CategoryExt categoryExt = new CategoryExt();
            categoryExt.setName(category.getName());
            categoryExt.setDescription(category.getDescription());
            categoryExt.setOrderNum(category.getOrderNum());
            categoryExt.setDeleted(category.getDeleted().equals("1") ? "被删除" : "未被删除");
            String parentName = getParentName(category.getParentId());//获取父栏目名称
            categoryExt.setParentId(parentName);
            resultList.add(categoryExt);
        }

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        EasyExcel.write(stream, CategoryExt.class)
                .sheet().doWrite(resultList);
        return resultList;
    }

    @Override
    public List<Category> importCategory(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        EasyExcel.read(fileName, Category.class,new CategoryListener(mapper)).sheet().doRead();
        return mapper.selectList(null);
    }

    //自定义方法获取父栏目名称
    private String getParentName(Integer parentId) {
        if(parentId == null){
            return "";
        }
        return mapper.selectById(parentId).getName();
    }
}
